package com.its.common.net.server.channel;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.Singleton;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.RemovalListener;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.Collection;
import java.util.concurrent.TimeUnit;

/**
 * @Author xiaxp
 * @Date 9/15/22 15:19
 * @Description
 */
@Slf4j
public class SocketAddrManager {

    RemovalListener<String, InetSocketAddress> removalListener = notification -> {
        log.warn("[" + notification.getKey() + ":" + notification.getValue() + "] 过期删除.");
    };

    Cache<String, InetSocketAddress> cache;

    private SocketAddrManager() {}

    public static SocketAddrManager getInstance() {
        return Singleton.get(SocketAddrManager.class);
    }

    public void init(long duration, TimeUnit unit){
        if(null != cache){
            return;
        }
        cache = CacheBuilder.newBuilder()
                .expireAfterAccess(duration, unit)
                .maximumSize(100000)
                .removalListener(removalListener)
                .build();
    }

    public void addInetSocketAddress(InetSocketAddress inetSocketAddress) {
        Assert.notNull(cache, "Cache尚未初始化.");

        String key = inetSocketAddress2HostPort(inetSocketAddress);
        
        if(null == cache.getIfPresent(key)) {
            cache.put(key, inetSocketAddress);
        }
    }

    public Collection<InetSocketAddress> getAllInetSocketAddress() {
        Assert.notNull(cache, "Cache尚未初始化.");
        return cache.asMap().values();
    }

    private String inetSocketAddress2HostPort(InetSocketAddress inetSocketAddress){
        return inetSocketAddress.getHostString() + "_" + inetSocketAddress.getPort();
    }
}
